<template>
    <div ref="myChart" :style="styles"></div>
</template>

<script>
import * as echarts from "echarts";
// 引入图组件
import "echarts/lib/chart/bar";
import "echarts/lib/chart/pie";
import "echarts/lib/chart/map";
import "echarts/lib/chart/line";
import "echarts/lib/chart/scatter";
import "echarts/lib/chart/graph";

// 引入工具组件
import "echarts/lib/component/legend";
import "echarts/lib/component/legendScroll";
import "echarts/lib/component/title";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/geo";
import "echarts/lib/component/dataZoom";

import { useChartEvents } from "./hooks";

export default {
    name: "VEcharts",
    props: {
        options: {
            type: Object,
            required: true,
        },
        styles: {
            type: [Object, String],
            default: () => ({
                width: "100%",
                height: "500px",
            }),
        },
    },
    data() {
        return {
            chart: null,
        };
    },
    watch: {
        options: {
            handler() {
                if (!this.options)
                    return console.error("error:Not-required-options");
                this.$nextTick(() => this.initEcharts());
            },
            deep: true,
            immediate: true,
        },
    },
    mounted() {
        setTimeout(() => {
            this.resizeHandler();
        }, 0);
    },
    destroyed() {
        if (!this.chart) {
            return;
        }
        window.removeEventListener("resize", this.resizeHandler);
        this.chart.dispose();
        this.chart = null;
    },
    methods: {
        initEcharts() {
            const { options } = this;
            this.chart = echarts.init(this.$refs.myChart);
            if (!this.chart) return console.error("error:Not-ref");
            if (options && typeof options === "object") {
                this.chart.setOption(options);
            }
            window.addEventListener("resize", () => {
                setTimeout(() => {
                    this.resizeHandler();
                }, 100);
            });
            const events = this.$listeners;
            useChartEvents(events, this.chart);
        },
        resizeHandler() {
            this.chart?.resize();
        },
    },
};
</script>

<style></style>
